#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2014-06-17 23:04:35
# @Author  : shitao.tommy (hero007asd@gmail.com)
# @Link    : http://example.org
# @Version : $Id$

import logging
import tornado
import tornado.web
import os
from tornado.httpserver import HTTPServer
from tornado.options import define, parse_command_line, options
from bootloader import settings

from lib.tornado_routes import make_handlers, get_all_handler
from lib import log, session
from framework.minirest import handler as h
from web.handler import BaseHandler

# define('cmd', default='runserver', metavar='runserver')   # python manage.py --cmd=syncdb
define('cmd', default='runserver', metavar='runserver|syncdb|add_crawler_workder')   # python manage.py --cmd=syncdb
define("port", default=8080, type=int)

# import tcelery
# tcelery.setup_nonblocking_producer()
class Application(tornado.web.Application):
    def __init__(self):
        URL_PREFIX = ''
        handlers = [
                    tornado.web.url(r"/static/(.+)", tornado.web.StaticFileHandler, dict(path=settings['static_path']), name='static_path'),
                    tornado.web.url(r"/upload/(.+)", tornado.web.StaticFileHandler, dict(path=settings['upload_path']), name='upload_path'),
                    tornado.web.url(r"/assets/(.+)", tornado.web.StaticFileHandler, dict(path=settings['assets_path']), name='assets_path'),
                    ]
        handlers += make_handlers(URL_PREFIX, get_all_handler(os.path.dirname(os.path.abspath(__file__)), 'web/handler/', 'web', 'handler'))
        if settings.get('debug', True):
            handlers += [tornado.web.url(r'/apidoc/doc/(.*)', h.ApidocHandler)]  #apidoc handler
        # 处理未捕获的路由，404页面
        handlers += [tornado.web.url(r'.*', BaseHandler)]

        tornado.web.Application.__init__(self, handlers, **settings)
        # 设置session容器，默认使用内存
        self.session_store = _init_session('redis')

def syncdb():
    '''同步数据库
    '''
    import models
    for model in models.get_all_model():
        # if model.table_exists():
        #     model.drop_table()
        # model.create_table()
        if not model.table_exists():
            model.create_table()
            logging.info('created table:%s' % model._meta.db_table)

def runserver():
    if settings.get('debug', True):
        http_server = HTTPServer(Application(), xheaders = True)
        http_server.listen(options.port)
    else:
        sockets=tornado.netutil.bind_sockets(options.port)
        tornado.process.fork_processes(0)
        http_server = HTTPServer(Application(), xheaders = True)
        http_server.add_sockets(sockets)
    tornado.ioloop.IOLoop.instance().start()
    # tornado.ioloop.PeriodicCallback(save_proxylist, 1*60*60*1000).start()
    logging.info("Server running  on http://0.0.0.0:%d" %(options.port))
    # sys.excepthook = log.log_exception

def _init_session(type='memory'):
    '''session store init
    '''
    if type == 'memory':
        return session.CommonSessionStore()
        # return session.FileSessionStore()
    elif type == 'memcache':
        return session.MemcacheSessionStore()
    elif type == 'redis':
        return session.RedisSessionStore()
    elif type == 'mysql':
        return session.MysqlSessionStore()
    else:
        return session.CommonSessionStore()



if __name__ == '__main__':
    parse_command_line()

    # log.init_log(settings['log_name'])
    log.init_log(settings['access_log'])
    log.init_log(settings['api_log'])
    log.init_log(settings['sql_log'])
    log.init_log(settings['err_log'])

    if options.cmd == 'syncdb':
        syncdb()
    else:
        runserver()
